//
//  DYShopDetailVC.m
//  TerritoryShopkeeper
//
//  Created by 黄德玉 on 2018/6/21.
//  Copyright © 2018年 ZDQK. All rights reserved.
//

#import "DYShopDetailVC.h"
#import "FiltrateFirstView.h"
#import "FiltrateSecondView.h"
#import "GoodsListCommonCell.h"
#import "GoodsListDoubleCell.h"
#import "GoodsDetailViewController.h"
#import "FiltrateRightView.h"
#import "GoodsListFiltrateModel.h"
#import "GoodsListFiltrateRightModel.h"
#import "SearchCacheViewController.h"

#import <Masonry/Masonry.h>
#import "DYShopModel.h"
#import "DYShopHeaderView.h"
#import "DYADWebVC.h"
#import "DYMyShopDetailVC.h"
#import "DYShopSXListView.h"

typedef NS_ENUM(NSInteger, GoodsListShowType) {
    GoodsListShowTypeForCommon,
    GoodsListShowTypeForDouble
};

@interface DYShopDetailVC ()<UITableViewDataSource, UITableViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate, UISearchBarDelegate>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) FiltrateFirstView *firstView;
@property (nonatomic, strong) FiltrateSecondView *secondView;

@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *secondArr;

@property (nonatomic, assign) GoodsListShowType showType;

@property (nonatomic, strong) FiltrateRightView *rightFiltrateView;
@property (nonatomic, strong) UIButton *rightButton;

@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) GoodsListFiltrateModel *filtrateModel;
@property (nonatomic, strong) GoodsListFiltrateRightModel *rightModel;

@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic,strong) DYShopHeaderView * headerView;

@property (nonatomic,assign) NSInteger shopType;    //0:全部 1：自营 2：代理
@end



@implementation DYShopDetailVC

- (instancetype)init {
    self = [super init];
    if (self) {
        self.title = @"商品";
        _showType = GoodsListShowTypeForCommon;
        _dataSource = [NSMutableArray array];
        _currentPage = 1;
        _filtrateModel = [[GoodsListFiltrateModel alloc] init];
        _filtrateModel.sort = @"1";
        _rightModel = [[GoodsListFiltrateRightModel alloc] init];
        _secondArr = [NSMutableArray array];
        _gcid = @"";
        _gtcid = @"";
        _gtrcid = @"";
        _keyword = @"";
        _isAbroad = NO;
        self.keyword = @"";
        self.shopType = 0;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor greenColor];
    [self configureUI];
    [self configureData];
    [self responseBlock];
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self loadNewData];
    [self loadHeader];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hiddenShadowImage:NO];
    [self navigationSetup];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}

- (void)navigationSetup {
    [self hideNavigationController];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHex:0xF23030 alpha:self.tableView.mj_offsetY > [self getNavAndStatusHeight]]] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    if (self.tableView.mj_offsetY > [self getNavAndStatusHeight]) {
        [self setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    } else {
        [self setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    }
}



- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
//    self.firstView.frame = CGRectMake(0, Height_Nav_Bar + Height_Nav_Status, self.view.width, 44);
//    self.secondView.frame = CGRectMake(0, self.firstView.bottom, self.view.width, 44);
}

#pragma mark - Method
- (void)configureUI {
    [self.view addSubview:self.headerView];
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
    }];
    [self.view addSubview:self.firstView];
    [self.firstView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.headerView.mas_bottom);
        make.height.equalTo(@44);
    }];
//    [self.view addSubview:self.secondView];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.top.equalTo(self.firstView.mas_bottom);
    }];
    
    // 导航栏搜索框
    [self.searchView addSubview:self.searchBar];
    self.searchView.frame = CGRectMake(0, 0, ScreenWidth - 15 * 4 - 28 * 2, 28);
    self.searchBar.frame = CGRectMake(0, 0, self.searchView.width, 28);
    self.navigationItem.titleView = self.searchView;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
//    self.navigationItem.hi
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"GoodsListCommonCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"commonCell"];
    [self.tableView registerClass:[GoodsListDoubleCell class] forCellReuseIdentifier:@"doubleCell"];
    [self.tableView clearExtendCellLine];
    
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.currentPage = 1;
        [weakSelf loadNewData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.currentPage += 1;
        [weakSelf loadNewData];
    }];
    [self.tableView.mj_footer setHidden:YES];
    
    self.searchBar.text = self.keyword;
}

- (void)loadHeader{
    [self.headerView loadData:self.shopInfo];
}

- (void)configureData {
    [self configureSecondArr];
    [self.secondView setValuesWithTitles:self.secondArr];
    __weak typeof(self) weakSelf = self;
    self.secondView.block = ^(NSInteger index) {
        FiltrateSecondModel *model = [weakSelf.secondArr objectAtIndex:index];
        model.isSelect = !model.isSelect;
        weakSelf.currentPage = 1;
        [weakSelf loadNewData];
    };
    
    ClassifyFirstModel *firstClassifyModel = [[ClassifyManager shareInstance] getClassifyFirstModelWithGcid:self.gcid];
    self.rightModel.attributeArr = [[ClassifyManager shareInstance] configureFiltrateModel:firstClassifyModel];
}

- (void)configureSecondArr {
    FiltrateSecondModel *model1 = [[FiltrateSecondModel alloc] init];
    model1.title = @"新品";
    model1.isSelect = NO;
    
    FiltrateSecondModel *model2 = [[FiltrateSecondModel alloc] init];
    model2.title = @"优惠券";
    model2.isSelect = NO;
    
    FiltrateSecondModel *model3 = [[FiltrateSecondModel alloc] init];
    model3.title = @"促销";
    model3.isSelect = NO;
    
    FiltrateSecondModel *model4 = [[FiltrateSecondModel alloc] init];
    model4.title = @"包邮";
    model4.isSelect = NO;
    
    [self.secondArr addObject:model1];
    [self.secondArr addObject:model2];
    [self.secondArr addObject:model3];
    [self.secondArr addObject:model4];
}

- (void)responseBlock {
    __weak typeof(self) weakSelf = self;
    self.firstView.block = ^(NSInteger index) {
        switch (index) {
            case 0: {
                weakSelf.filtrateModel.sort = @"1";
                weakSelf.currentPage = 1;
                [weakSelf loadNewData];
            } break;
            case 1: {
                weakSelf.filtrateModel.sort = @"2";
                weakSelf.currentPage = 1;
                [weakSelf loadNewData];
            } break;
            case 3: {
                [weakSelf showFiltrateRightView];
            } break;
            case 4: {
                weakSelf.filtrateModel.sort = @"3";
                weakSelf.currentPage = 1;
                [weakSelf loadNewData];
            } break;
            case 5: {
                weakSelf.filtrateModel.sort = @"4";
                weakSelf.currentPage = 1;
                [weakSelf loadNewData];
            } break;
            default:
                break;
        }
    };
}

- (void)showFiltrateRightView {
//    __weak typeof(self) weakSelf = self;
//    if (!self.rightFiltrateView) {
//        self.rightFiltrateView = [[FiltrateRightView alloc] initWithRightModel:self.rightModel block:^(GoodsListFiltrateRightModel *rightModel) {
//            weakSelf.rightModel = rightModel;
//            weakSelf.currentPage = 1;
//            [weakSelf loadNewData];
//        }];
//    }
//    [self.rightFiltrateView showFromRight];
    
//    [DYShopSXListView showInView:nil WithRect:[self.firstView.fourthLabel convertRect:self.firstView.fourthLabel] toView: callback:^(id value) {
//
//    }];
    CGRect rect = [self.firstView.fourthLabel convertRect:self.firstView.fourthLabel.bounds toView:nil];
    __weak typeof(self) weakSelf = self;
    [DYShopSXListView showInView:nil WithRect:rect currentSelected:self.shopType callback:^(id value) {
        NSInteger current = [value integerValue];
        weakSelf.shopType = current;
        [weakSelf loadNewData];
    }];
//    self.firstView
}

#pragma mark - Action
- (void)rightItemClick {
    if (self.showType == GoodsListShowTypeForCommon) {
        self.showType = GoodsListShowTypeForDouble;
        [self.rightButton setImage:[UIImage imageNamed:@"screen"] forState:UIControlStateNormal];
    } else {
        self.showType = GoodsListShowTypeForCommon;
        [self.rightButton setImage:[UIImage imageNamed:@"portrait"] forState:UIControlStateNormal];
    }
    [self.tableView reloadData];
}
- (NSString *)getGtrcid {
    NSString *gtrcid = @"";
    for (FiltrateFirstModel *firstModel in self.rightModel.attributeArr) {
        if (firstModel.isShow) {
            for (FiltrateSecondModel *secondModel in firstModel.secondList) {
                if (secondModel.isSelect) {
                    if (TextIsNotNil(gtrcid)) {
                        gtrcid = [NSString stringWithFormat:@"%@,%@",gtrcid,secondModel.gtrcid];
                    } else {
                        gtrcid = secondModel.gtrcid;
                    }
                }
            }
        }
    }
    if (TextIsNotNil(gtrcid)) {
        return gtrcid;
    }
    return self.gtrcid;
}
#pragma mark - NetWork
- (void)loadNewData {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@(self.currentPage) forKey:@"pageNumber"];
    [parameters setObject:PageSize forKey:@"pageSize"];
    
    [parameters setObject:self.filtrateModel.sort forKey:@"sort"]; // 排序(1推荐2销量3价格升4价格降)
    
    FiltrateSecondModel *model1 = [self.secondArr objectAtIndex:0];
    FiltrateSecondModel *model2 = [self.secondArr objectAtIndex:1];
    FiltrateSecondModel *model3 = [self.secondArr objectAtIndex:2];
    FiltrateSecondModel *model4 = [self.secondArr objectAtIndex:3];
    
    
    [parameters setObject:self.filtrateModel.isrecommend forKey:@"isrecommend"]; // 是否推荐(1是0否)
    [parameters setObject:self.filtrateModel.issalesvolume forKey:@"issalesvolume"]; // 销量(1是0否)
    [parameters setObject:self.filtrateModel.isprice forKey:@"isprice"]; // 价格(0否1升序2降序)
    [parameters setObject:model1.isSelect ? @"1" : @"0" forKey:@"isnew"];   // 是否新品(1是0否)
    [parameters setObject:model2.isSelect ? @"1" : @"0" forKey:@"isdiscount"]; // 是否优惠劵(1是0否)
    [parameters setObject:model3.isSelect ? @"1" : @"0" forKey:@"ispromotion"]; // 是否促销(1是0否)
    [parameters setObject:model4.isSelect ? @"1" : @"0" forKey:@"isfreeshipping"]; // 是否包邮(1是0否)
    //[parameters setObject:self.gcid forKey:@"gcid"];     // 一级分类id集合
    //[parameters setObject:self.gtcid forKey:@"gtcid"];   // 二级分类id集合
    [parameters setObject:[self getGtrcid] forKey:@"gtrcid"];    // 三级分类id集合
    [parameters setObject:self.rightModel.minPrice forKey:@"pricemin"]; // 价格1
    [parameters setObject:self.rightModel.maxPrice forKey:@"pricemax"]; // 价格2
    [parameters setObject:self.keyword forKey:@"gname"];
    
    DYShopModel * model = [DYShopModel mj_objectWithKeyValues:self.shopInfo];
    [parameters safeSetObject:model.sid forKey:@"sid"];
    
//    NSString *url = URL_Get_Goods_List;
//    if (self.isAbroad) {
//        url = URL_Get_Abroad_Goods_List;
//    }
    [parameters setObject:@(self.shopType) forKey:@"type"];
    NSString * url = @"api2/getShopInfo";
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:url parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        
        if (code && [code isEqualToString:@"200"]) {
            
            NSDictionary *data = [responseDic safeJsonObjectForKey:@"data"];
            NSDictionary * page = [data safeObjectForKey:@"page"];
            NSArray *list = [page safeJsonObjectForKey:@"list"];
            NSString *totalPage = [page safeObjectForKey:@"totalPage"];
            if (weakSelf.currentPage == totalPage.integerValue || totalPage.integerValue == 0) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                [weakSelf.tableView.mj_footer setHidden:YES];
            } else {
                [weakSelf.tableView.mj_footer resetNoMoreData];
                [weakSelf.tableView.mj_footer setHidden:NO];
            }
            
            if (weakSelf.currentPage == 1) {
                [weakSelf.dataSource removeAllObjects];
            }
            
            for (NSDictionary *modelDic in list) {
                GoodsListModel *model = [GoodsListModel mj_objectWithKeyValues:modelDic];
                [weakSelf.dataSource addObject:model];
            }
            
            weakSelf.searchBar.text = weakSelf.keyword;
            [weakSelf.tableView reloadData];
            
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:code animated:YES];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.showType == GoodsListShowTypeForCommon) {
        return self.dataSource.count;
    } else {
        return [GoodsListDoubleCell getRowNumberWithItemArr:self.dataSource];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.showType == GoodsListShowTypeForCommon) {
        GoodsListCommonCell *commonCell = [tableView dequeueReusableCellWithIdentifier:@"commonCell" forIndexPath:indexPath];
        GoodsListModel *model = [self.dataSource objectAtIndex:indexPath.row];
        [commonCell setValueForCellWithModel:model];
        return commonCell;
    } else {
        GoodsListDoubleCell *doubleCell = [tableView dequeueReusableCellWithIdentifier:@"doubleCell" forIndexPath:indexPath];
        NSArray *arr =  [GoodsListDoubleCell getCellItemArr:self.dataSource withIndexPath:indexPath];
        [doubleCell setValuesForCellWithItems:arr];
        
        __weak typeof(self) weakSelf = self;
        doubleCell.block = ^(NSInteger index) {
            GoodsListModel *model = [arr objectAtIndex:index];
            if (!model.isshelves) {
                [MBProgressHUD showError:weakSelf.view title:@"该商品已下架" code:@"" animated:YES];
                return;
            }
            GoodsDetailViewController *detailVC = [[GoodsDetailViewController alloc] init];
            detailVC.gid = model.gid;
            [weakSelf.navigationController pushViewController:detailVC animated:YES];
        };
        
        return doubleCell;
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.showType == GoodsListShowTypeForCommon) {
        return [GoodsListCommonCell getHeight];
    } else {
        return [GoodsListDoubleCell getHeight];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.showType == GoodsListShowTypeForCommon) {
        GoodsListModel *model = [self.dataSource objectAtIndex:indexPath.row];
        if (!model.isshelves) {
            [MBProgressHUD showError:self.view title:@"该商品已下架" code:@"" animated:YES];
            return;
        }
        GoodsDetailViewController *detailVC = [[GoodsDetailViewController alloc] init];
        detailVC.gid = model.gid;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"暂无商品"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    self.currentPage = 1;
    [self loadNewData];
}

#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    BOOL searchVC = NO;
    for (UIViewController *viewController in self.navigationController.viewControllers) {
        if ([viewController isKindOfClass:[SearchCacheViewController class]]) {
            searchVC = YES;
            [self.navigationController popToViewController:viewController animated:YES];
            
        }
    }
    if (!searchVC) {
        SearchCacheViewController *searchCacheVC = [[SearchCacheViewController alloc] init];
        searchCacheVC.type = SearchCacheViewControllerTypeForList;
        __weak typeof(self) weakSelf = self;
        searchCacheVC.block = ^(NSString *keyword) {
            weakSelf.keyword = keyword;
            weakSelf.currentPage = 1;
            [weakSelf loadNewData];
        };
        [self.navigationController pushViewController:searchCacheVC animated:YES];
    }
    
    return NO;
}

#pragma mark - Getters
- (FiltrateFirstView *)firstView {
    if (!_firstView) {
        _firstView = [[FiltrateFirstView alloc] initWithType:FiltrateTypeFour];
    }
    return _firstView;
}

- (FiltrateSecondView *)secondView {
    if (!_secondView) {
        _secondView = [[FiltrateSecondView alloc] init];
    }
    return _secondView;
}

- (UIButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightButton addTarget:self action:@selector(rightItemClick) forControlEvents:UIControlEventTouchUpInside];
        [_rightButton setImage:[UIImage imageNamed:@"portrait"] forState:UIControlStateNormal];
    }
    return _rightButton;
}

- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] init];
        [_searchView.layer setCornerRadius:14];
        _searchView.clipsToBounds = YES;
        [_searchView setBackgroundColor:[UIColor colorWithHex:0xEAEBED  alpha:1.0]];
    }
    return _searchView;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.delegate = self;
        [_searchBar setTintColor:[UIColor blueColor]];
        _searchBar.backgroundImage = [UIImage imageWithColor:[UIColor whiteColor]];
        //        [_searchBar changeLeftPlaceholder:@"搜索你想要的"];
        _searchBar.placeholder = @"搜索你感兴趣的商品";
        
        UITextField *searchField = [_searchBar valueForKey:@"searchField"];
        searchField.mj_h = 28;
        [searchField.layer setCornerRadius:14];
        //[searchField.layer setBorderWidth:0.5];
        searchField.backgroundColor = [UIColor colorWithHex:0xEAEBED  alpha:1.0];
        [searchField.layer setBorderColor:[UIColor lightGrayColor].CGColor];
        searchField.layer.masksToBounds = YES;
        searchField.font = TextPingFangFontSize(14);
        
    }
    return _searchBar;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
    }
    return _tableView;
}

- (DYShopHeaderView *)headerView{
    if (!_headerView) {
        _headerView = [[DYShopHeaderView alloc] init];
        __weak typeof(self) weakSelf = self;
        _headerView.didClickedAD = ^(id data) {
            NSString * atype = [data safeStringForKey:@"atype"];
            NSString * gid = [data safeStringForKey:@"alink"];
            if ([atype isEqualToString:@"0"]) { //跳转到商品详情
                GoodsDetailViewController * vc = [[GoodsDetailViewController alloc] init];
                vc.type = GoodsDetailViewControllerTypeForNormal;
                vc.gid = gid;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }else if ([atype isEqualToString:@"1"]){ //外链链接
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:gid]];
            }else if ([atype isEqualToString:@"2"]){ //h5
                DYADWebVC * vc = [[DYADWebVC  alloc] init];
                vc.urlStr = gid;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }
        };
        _headerView.didClickedShopName = ^{
            DYMyShopDetailVC * vc = [[DYMyShopDetailVC alloc] init];
            DYShopModel * model = [DYShopModel mj_objectWithKeyValues:weakSelf.shopInfo];
            vc.sid = model.sid;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
    }
    return _headerView;
}
@end
